package com.central.apps.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.central.app.service.HandlerService;
import com.central.apps.util.GetDirPathUtil;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JHY
 */
@Slf4j
@Api(tags = "在线编辑接口")
@CrossOrigin
@RestController
@RequestMapping("/onlineEditing")
public class OnlineEditingController {
    private String dir = GetDirPathUtil.getDirPath() + "static/doc/";

    @Value("${officepath}")
    private String baseDir;

    @Autowired
    private HandlerService handlerService;

    @GetMapping("/openContract")
    public Object findOperationLogById(String fileid, String access_token, HttpServletRequest request) {
        System.err.println("enter openContract");
        log.info("enter openContract");
        List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where appname = 'contracttemplateApp' and fileid =" + fileid + "");
        System.err.println(JSON.toJSONString(fileList));
        String pathname = MapUtil.getStr(fileList.get(0), "filepath");
        String pathid = MapUtil.getStr(fileList.get(0), "pathid");

        List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
        String filepath = MapUtil.getStr(pathList.get(0), "pathname");
        System.err.println("cx:" + pathname);
        if (StringUtils.isNotBlank(pathname)) {
            String[] split = pathname.split("/");
            pathname = "/" + split[split.length - 1];
        }
        String pt = filepath + pathname;
        System.err.println("文件路径:" + pt);
        log.info("文件路径:" + pt);

        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setServerPage("/api-apps/office/poserver.zz");
        //设置PageOffice控件标题栏内容
        poCtrl.setCaption("EAM合同模板在线编辑");
        poCtrl.setSaveFilePage("/api-apps/onlineEditing/save?access_token=" + access_token + "&fileid=" + fileid);

        poCtrl.addCustomToolButton("保存", "Save", 1);
        poCtrl.addCustomToolButton("另存为", "SaveAs", 12);
        poCtrl.addCustomToolButton("打印设置", "PrintSet", 0);
        poCtrl.addCustomToolButton("打印", "PrintFile", 6);
        poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen", 4);
        poCtrl.addCustomToolButton("-", "", 0);
        poCtrl.addCustomToolButton("关闭", "Close", 21);
        poCtrl.webOpen("file://" + pt, OpenModeType.docAdmin, "张三");
        return poCtrl.getHtmlCode("PageOfficeCtrl1");
    }

    @GetMapping("/SetDrByUserWord")
    public Object SetDrByUserWord(HttpServletRequest request) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setServerPage("/poserver.zz");
        //设置PageOffice控件标题栏内容
        poCtrl.setCaption("EAM合同模板在线编辑");
        poCtrl.setSaveFilePage("/onlineEditing/save");

        String userName = "zhangsan";
        //***************************卓正PageOffice组件的使用********************************
        WordDocument doc1 = new WordDocument();
        //打开数据区域
        DataRegion dTitle = doc1.openDataRegion("PO_title");
        //给数据区域赋值
        dTitle.setValue("某公司第二季度产量报表");
        //设置数据区域可编辑性
        //数据区域不可编辑
        dTitle.setEditing(false);

        DataRegion dA1 = doc1.openDataRegion("PO_A_pro1");
        DataRegion dA2 = doc1.openDataRegion("PO_A_pro2");
        DataRegion dB1 = doc1.openDataRegion("PO_B_pro1");
        DataRegion dB2 = doc1.openDataRegion("PO_B_pro2");

        //根据登录用户名设置数据区域可编辑性
        //A部门经理登录后
        if (userName.equals("zhangsan")) {
            userName = "A部门经理";
            dA1.setEditing(true);
            dA2.setEditing(true);
            dB1.setEditing(false);
            dB2.setEditing(false);
        }
        //B部门经理登录后
        else {
            userName = "B部门经理";
            dB1.setEditing(true);
            dB2.setEditing(true);
            dA1.setEditing(false);
            dA2.setEditing(false);
        }

        poCtrl.setWriter(doc1);
        //添加自定义按钮
        poCtrl.addCustomToolButton("保存", "Save", 1);
        poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen", 4);
        //隐藏标题栏
        poCtrl.setTitlebar(false);
        //隐藏菜单栏
        poCtrl.setMenubar(false);
        //隐藏Office工具条
        poCtrl.setOfficeToolbars(false);
        //打开word
        poCtrl.webOpen(baseDir + "SetDrByUserWord/test.doc", OpenModeType.docSubmitForm, "张三");
        Map<String, Object> map = new HashMap<>();
        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
        map.put("userName", userName);
        return map;
    }

    @GetMapping("/RevisionOnly")
    public Object RevisionOnly(HttpServletRequest request) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setServerPage("/poserver.zz");
        //添加自定义按钮
        poCtrl.addCustomToolButton("保存", "Save", 1);
        poCtrl.addCustomToolButton("隐藏痕迹", "hideRevision", 18);
        poCtrl.addCustomToolButton("显示痕迹", "showRevision", 9);
        //设置保存页面
        poCtrl.setSaveFilePage("/onlineEditing/RevisionOnly/save");
        //打开Word文档
        poCtrl.webOpen(baseDir + "RevisionOnly/test.doc", OpenModeType.docRevisionOnly, "张三");
        return poCtrl.getHtmlCode("PageOfficeCtrl1");
    }

    @GetMapping("/InsertSeal/Word/AddSeal/Word1")
    public Object InsertSealAddSeal(HttpServletRequest request) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setServerPage("/poserver.zz");
        //添加自定义按钮
        poCtrl.addCustomToolButton("保存", "Save", 1);
        poCtrl.addCustomToolButton("加盖印章", "InsertSeal()", 2);
        poCtrl.addCustomToolButton("删除印章", "DeleteSeal()", 21);
        poCtrl.addCustomToolButton("验证印章", "VerifySeal()", 5);
        poCtrl.addCustomToolButton("修改密码", "ChangePsw()", 0);
        //设置保存页面
        poCtrl.setSaveFilePage("/onlineEditing/InsertSeal/Word/AddSeal/save");
        //打开Word文档
        poCtrl.webOpen(baseDir + "InsertSeal/Word/AddSeal/test1.doc", OpenModeType.docNormalEdit, "张三");
        return poCtrl.getHtmlCode("PageOfficeCtrl1");
    }

    @RequestMapping("/RevisionOnly/save")
    public void RevisionOnlySave(HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(baseDir + "RevisionOnly/" + fs.getFileName());
        fs.close();
    }

    @RequestMapping("/InsertSeal/Word/AddSeal/save")
    public void InsertSealSave(HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(baseDir + "InsertSeal/Word/AddSeal/" + fs.getFileName());
        fs.close();
    }

    @RequestMapping("save")
    public void save(String fileid, HttpServletRequest request, HttpServletResponse response) {
        System.err.println("enter save");
        List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where appname = 'contracttemplateApp' and fileid =" + fileid + "");
        System.err.println(JSON.toJSONString(fileList));
        String pathid = MapUtil.getStr(fileList.get(0), "pathid");
        List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
        String filepath = MapUtil.getStr(pathList.get(0), "pathname");

        FileSaver fs = new FileSaver(request, response);
        String filePath = filepath + "/" + fs.getFileName();
        fs.saveToFile(filePath);
        fs.close();
    }


}
